package com.breeze.leetcode.middle;

/**
 * @url <a href="https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/">80. 删除有序数组中的重复项 II</a>
 */
public class T80RemoveDuplicatesFromSortedArrayII {
    public static void main(String[] args) {
        T80RemoveDuplicatesFromSortedArrayII solution = new T80RemoveDuplicatesFromSortedArrayII();
        // {0,0,1,1,1,1,2,3,3}
        int[] nums = {0,0,1,1,1,1,2,3,3};

        int len = solution.removeDuplicates(nums);
        System.out.println(len);
        for (int i = 0; i < len; i++) {
            System.out.print(nums[i]);
        }
    }

    /**
     * 原地删除数组的值，数组升序排列，不需要考虑数组中超出新长度后面的元素
     * 每个元素有且最多只有两个
     * @ideas 双指针，i:当前遍历位置，flag:下一种元素的位置（当前元素的第三个的位置），cursor:
     * @answer 快慢指针，实际上是用后续的值覆盖前面多余的值
     */
    public int removeDuplicates(int[] nums) {
        int len  = nums.length;
        if (len <= 2) {
            return len;
        }

        int slow = 2, fast = 2;
        while (fast < len) {
            if (nums[slow - 2] != nums[fast]) {
                nums[slow] = nums[fast];
                slow++;
            }
            fast++;
        }

        return slow;
    }
}
